#include "stdafx.h"
#include "Background.h"
#include "Claxa.h"
#include "CXComp.h"
#include <xml/stream.h>
#include <MyControls/Xml.h>

Background::Background(CXComp & comp) :
	m_Comp(comp)
{
}

bool Background::OpenDialog(Extent const & RequiredDim)
{
	theApp.BeginActivity("loading footage");
	FootageSPtr f = theApp.m_Cache.create_footage_dialog(true, theApp.GetMainWnd()->m_hWnd);
	theApp.EndActivity();

	if (!f)
		return false;
	if (f->dim() != RequiredDim) {
		CString msg;
		msg.Format(
			"Dimensions of the footage (%s) differ from composition dimensions.\n"
			"Therefore, its loading as a background is prohibited, sorry.", f->filepath().c_str());
		AfxMessageBox(msg, MB_ICONEXCLAMATION, 0);
		return false;
	}

	m_pFootage.swap(f);
		
	SetTrimming(GetMaxPossibleTrimming());
	DispatchEvent(Layer::StateChange(* this));

	m_Comp.GetActions().Modified();

	return true;
}

void Background::Close()
{
	m_pFootage.reset();
	DispatchEvent(Layer::StateChange(* this));
}

xml::stream & Background::Serialize(xml::stream & s, const String & BasePath)
{
	using namespace xml;

	if (s.in() && s.root().null()) {
		Close();
		return s;
	}

	s.child("Footage") || 
		icache::footage_ptr_capsule(theApp.m_Cache, m_pFootage, BasePath);
	s || def_attr("SourceOffset", m_SourceOffset);

	if (s.in()) {
		Span t;
		s || child("Trimming", t);
		if (t.Empty())
			t = GetMaxPossibleTrimming();
		SetTrimming(t);
		DispatchEvent(TimeSpanChange(* this));
		DispatchEvent(StateChange(* this));
	} else {
		s || child("Trimming", m_Trimming);
	}

	return s;
}

Size Background::GetSourceDuration() const
{
	return IsStill() ? m_Comp.GetDuration() : 
		m_pFootage->size();
}

bool Background::IsSelected() const
{
	return false;
}

void Background::Select(bool on)
{
}

void Background::SetSourceOffset(int t)
{
	if (m_SourceOffset != t) {
		m_SourceOffset = t;
		DispatchEvent(TimeSpanChange(* this));
	}
}

void Background::SetTrimming(Span s)
{
	if (!s.Valid())
		return;
	if (!IsStill())
		s.Intersect(GetMaxPossibleTrimming());
	if (m_Trimming != s) {
		m_Trimming = s;
		DispatchEvent(TrimmingChange(* this));
	}
}
